package com.yyg.boot.web;

import com.yyg.boot.util.AliyunOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;

@Controller
public class OssController {

    @Autowired
    private AliyunOssUtil ossUtil;

    @GetMapping("/")
    public String showUploadFile() {
        return "upLoad";
    }

    @PostMapping("/uploadFile")
    public String upload(@RequestParam("file") MultipartFile file) {
        try {
            if (file != null) {
                String fileName = file.getOriginalFilename();
                if (!"".equals(fileName.trim())) {
                    File newFile = new File(fileName);
                    
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();

                    //把file里的内容复制到奥newFile中
                    file.transferTo(newFile);
                    String upload = ossUtil.upload(newFile);

                    //图片回显地址:
                    //http://yiyige.oss-cn-hangzhou.aliyuncs.com/images/2019-10-21/6c964702b67d4eeb920e7f1f4358189b-dishu.jpg
                    System.out.println("path=" + upload);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "success";
    }

}

